/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/graph/core/optimize/fusion/pattern_pass.h"

#include "infra/base/assertion.h"

#include "framework/common/fmk_error_codes.h"

namespace hiai {
OptimizeStatus PatternPass::Run(ge::Node& node, ge::ComputeGraph& graph)
{
    if (patterns_.empty()) {
        patterns_ = DefinePatterns();
    }

    OptimizeStatus optimizeStatus = OptimizeStatus::OPTIMIZE_NOT_CHANGED;
    for (const auto& pattern : patterns_) {
        auto patternMapping = const_cast<PatternDefine*>(pattern)->Match(node, graph);
        if (patternMapping == nullptr) {
            continue;
        }

        Status status = Fusion(graph, patternMapping);
        if (status != SUCCESS && status != hiai::NOT_CHANGED &&
            status != static_cast<Status>(OptimizeStatus::OPTIMIZE_NOT_CHANGED)) {
            return OptimizeStatus::OPTIMIZE_FAILED;
        } else if (status == SUCCESS) {
            optimizeStatus = OptimizeStatus::OPTIMIZE_CHANGED;
        }
    }

    return optimizeStatus;
}
} // namespace hiai